package wb.is.besti.edu.cd.emergency_responsesys.pages;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.PlanNode;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cc.trity.floatingactionbutton.FloatingActionButton;
import wb.is.besti.edu.cd.emergency_responsesys.R;
import wb.is.besti.edu.cd.emergency_responsesys.ui.AddMessageActivity;
import wb.is.besti.edu.cd.emergency_responsesys.ui.EventActivity;
import wb.is.besti.edu.cd.emergency_responsesys.utils.Events;
import wb.is.besti.edu.cd.emergency_responsesys.utils.HttpUtil;
import wb.is.besti.edu.cd.emergency_responsesys.utils.LocationManager;
import wb.is.besti.edu.cd.emergency_responsesys.utils.MarkeInfo;
import wb.is.besti.edu.cd.emergency_responsesys.widget.MyOrientationListener;

public class BaiDuMapFragment extends Fragment
{
    private BaiduMap baiduMap;
    private MapView mapView;
    private List<String> permissionList ;
    private LocationClient mLocationClient;
    private float mCurrentX;
    private double currentLatitude, currentLongitude, changeLatitude, changeLongitude;
    private TextView current_addr;
    private boolean isFirstLoc = true;
    public MyLocationListenner myListener = new MyLocationListenner();
    LatLng currentLL;
    PlanNode startNodeStr;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyOrientationListener myOrientationListener;
    private BitmapDescriptor  dragLocationIcon, bikeIcon;
    private List<MarkeInfo> infos = new ArrayList<>();
    private List<Events> eventslist =new ArrayList<>();
    private FloatingActionButton refresh;
    private TextView eventDes;
    private Button share;
    private Button readmore;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        SDKInitializer.initialize(getActivity().getApplicationContext());
        View view = inflater.inflate(R.layout.mappage_second,container,false);
        getPermissions();
        initview(view);
        initButton();
        new Thread(){
            @Override
            public void run() {
                eventslist = getEventList();
            }
        }.start();
        try {
            Thread.sleep(200);
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        initMap(view);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initMap(View view){
        mapView = (MapView)view.findViewById(R.id.baidu_map);
        mapView.showScaleControl(false);
        mapView.showZoomControls(false);
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(this.getActivity().getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(8000);//设置onReceiveLocation()获取位置的频率
        option.setIsNeedAddress(true);//如想获得具体位置就需要设置为true
        option.setLocationNotify(true);
        option.setIsNeedLocationDescribe(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
        baiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode,true,null));
        myOrientationListener = new MyOrientationListener(this.getContext());
        myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mCurrentX = x;
            }
        });
        myOrientationListener.start();
        initMarkerClickEvent();
    }

    private void getPermissions(){
        permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()){
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            BaiDuMapFragment.this.requestPermissions(permissions,1);
        }
    }

    private void initview(View view){
        current_addr = (TextView)view.findViewById(R.id.tv_position);
        bikeIcon = BitmapDescriptorFactory.fromResource(R.mipmap.drag_location);
        dragLocationIcon = BitmapDescriptorFactory.fromResource(R.mipmap.drag_location);
        refresh = (FloatingActionButton)view.findViewById(R.id.refresh);
        eventDes = (TextView)view.findViewById(R.id.news_desc);
        share = (Button)view.findViewById(R.id.btn_share);
        readmore=(Button)view.findViewById(R.id.btn_more);

    }
    public void getMyLocation() {
        LatLng latLng = new LatLng(currentLatitude, currentLongitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        baiduMap.setMapStatus(msu);
    }

    private StringBuilder currentPosition;
    public class MyLocationListenner implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation== null||mapView==null){
                return;
            }
            MyLocationData locData =  new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius()).direction(mCurrentX)
                    .latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
            currentLatitude = bdLocation.getLatitude();
            currentLongitude = bdLocation.getLongitude();
             currentPosition = new StringBuilder();
            currentPosition.append("位置:").append(bdLocation.getAddrStr()).append("\n");
            current_addr.setText(currentPosition);
            currentLL = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
            System.out.println(bdLocation.getLatitude()+"/"+bdLocation.getLongitude());
            LocationManager.getInstance().setCurrentLL(currentLL);
            LocationManager.getInstance().setAddress(bdLocation.getAddrStr());
            if (isFirstLoc){
                isFirstLoc = false;
                LatLng ll = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                changeLatitude = bdLocation.getLatitude();
                changeLongitude = bdLocation.getLongitude();
                currentPosition.delete(0,currentPosition.length()-1);
                currentPosition.append("位置:").append(bdLocation.getAddrStr()).append("\n");
            }
            if (!isFirstLoc){
                addOverLayouts(eventslist);
                isFirstLoc=true;
            }
        }
    }
    private String latlng(String regexStr, String str) {
        Pattern pattern = Pattern.compile(regexStr);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            str = matcher.group(1);
        }
        return str;
    }

    private void addInfosOverlay(List<MarkeInfo> infos){
        LatLng latLng = null;
        OverlayOptions overlayOptions = null;
        Marker marker = null;
        for (MarkeInfo info:infos){
            latLng = new LatLng(info.getLatitude(),info.getLongitude());
            // 图标
            overlayOptions = new MarkerOptions().position(latLng)
                    .icon(bikeIcon);
            marker = (Marker) (baiduMap.addOverlay(overlayOptions));
            Bundle bundle = new Bundle();
            bundle.putSerializable("info", info);
            marker.setExtraInfo(bundle);
        }
    }

    private void addOverLayouts(List<Events> list){
        baiduMap.clear();
        mLocationClient.requestLocation();
        infos.clear();
        for (Events events:list){
            infos.add(new MarkeInfo(events.getLatitude(),events.getLongitude(),events.getTitle(),events));
        }
        System.out.println("info"+":"+infos);
        addInfosOverlay(infos);
    }

    private MarkeInfo markeInfo;

    private void initMarkerClickEvent(){
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker!=null&&marker.getExtraInfo()!=null){
                     markeInfo = (MarkeInfo)marker.getExtraInfo().get("info");
                    if (markeInfo!=null){
                        /*String mes = String.valueOf(markeInfo.getLatitude());
                        Toast.makeText(BaiDuMapFragment.this.getContext(),mes,Toast.LENGTH_LONG).show();*/
                        /*Intent intent = EventActivity.newIntent(getContext(),markeInfo);
                        startActivity(intent);*/
                        initEventItem(markeInfo);
                    }
                }
                return true;
            }
        });
    }

    private void initEventItem(MarkeInfo markeInfo){
        current_addr.setText(markeInfo.getEvents().getPosition());
        eventDes.setText(markeInfo.getEvents().getDesc());
    }

    private void refreshItem(){
        current_addr.setText(currentPosition);
        eventDes.setText("");
    }

    private void initButton(){
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshEventList();
                addOverLayouts(eventslist);
                refreshItem();
            }
        });

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eventDes.getText()==""){
                    AddMessageActivity.startActivity(BaiDuMapFragment.this.getContext());
                }
                else {
                    Intent intent=new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                    intent.putExtra(Intent.EXTRA_TEXT, markeInfo.getEvents().getDesc());
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    BaiDuMapFragment.this.startActivity(Intent.createChooser(intent, markeInfo.getName()));
                }
            }
        });

        readmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eventDes.getText()==""){
                    AddMessageActivity.startActivity(BaiDuMapFragment.this.getContext());
                }
                else {
                    Intent intent = EventActivity.newIntent(getContext(),markeInfo);
                    startActivity(intent);
                }
            }
        });
    }

    private void refreshEventList(){
        new Thread(){
            @Override
            public void run() {
                eventslist = getEventList();
            }
        }.start();
        try {
            Thread.sleep(200);
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    private List<Events> getEventList(){
        List<Events> eventsList = new ArrayList<>();
        try {
            HttpUtil httpUtil = new HttpUtil();
            eventsList = httpUtil.getMarkerList();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return eventsList;
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }


    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }
}

